﻿using System;
using System.Data.Common.CommandTrees;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace ELinqParser
{
    class EfParser
    {
        public static DbExpression ConvertExpression(IQueryable q, ObjectContext db)
        {
            var assembly = typeof(DbExpression).Assembly;

            //Funcletizer funcletizer = Funcletizer.CreateQueryFuncletizer(this.ObjectContext);
            Type funcType = assembly.GetType("System.Data.Objects.ELinq.Funcletizer");
            MethodInfo createQueryFuncletizer = funcType.GetMethod("CreateQueryFuncletizer",
                                                                   BindingFlags.NonPublic | BindingFlags.Static);

            var funcletizer = createQueryFuncletizer.Invoke(null, new[] { db });

            // ExpressionConverter converter = new ExpressionConverter(funcletizer, _expression);
            var converterType = assembly.GetType("System.Data.Objects.ELinq.ExpressionConverter");
            ConstructorInfo createConverter =
                converterType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null,
                                             new[] { funcType, typeof(Expression) }, null);
            var converter = createConverter.Invoke(new[] { funcletizer, q.Expression });

            // var model = converter.Convert();
            MethodInfo convert = converterType.GetMethod("Convert", BindingFlags.NonPublic | BindingFlags.Instance);
            return (DbExpression)convert.Invoke(converter, null);
        }
    }
}
